#include "gameroom.h"
#include<QPainter>
#include<QIcon>
#include<QTimer>
#include<QPushButton>
#include<QSound>
#include<QMessageBox>
#include<QFile>
#include<QTextStream>
#include<QLabel>
#include<QTime>



GameRoom::GameRoom(QWidget *parent) : QWidget(parent)
{
    this->setWindowIcon(QIcon(":res/WidgetLogo.png"));
    this->setWindowTitle("贪吃蛇大作战");
    qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));

//    //初始化贪吃蛇
    snakeList.push_back(QRectF(400,400,SnakeWidth,SnakeHeight));
    //snakeList.push_back(QRectF(this->width()*0.5,this->height()*0.5,SnakeWidth,SnakeHeight));

    moveUP();
    moveUP();
//    moveUP();
//    moveUP();
//    moveUP();
//    moveUP();
//    moveUP();
//    moveUP();
//    moveUP();
//    moveUP();

    createNewFood();

    timer=new QTimer(this);//定时器
    connect(timer,&QTimer::timeout,[=]{
        int cnt=1;
        if(snakeList.front().intersects(foodRect))//判断蛇头和食物是否相交
        {
            createNewFood();
            cnt++;
        }
        while(cnt--)
        {
            switch (moveDirect) {
            case move_direction::UP:
                moveUP();
                break;
            case move_direction::DOWN:
                moveDown();
                break;
            case move_direction::LEFT:
                moveLeft();
                break;
            case move_direction::RIGHT:
                moveRight();
                break;
            }
        }
        snakeList.pop_back();
        update();
    });

    //开始游戏和暂停游戏控件
    QPushButton* starBtn=new QPushButton(this);
    QPushButton* stopBtn=new QPushButton(this);
    QFont font("宋体",20);

    //开始游戏控件
    starBtn->move(830,150);
    starBtn->setText("开始游戏");
    starBtn->setFont(font);
    connect(starBtn,&QPushButton::clicked,[=]{
        isready=true;
        timer->start(moveSpeed);
        sound = new QSound(":res/backgroundMusic.wav");
        sound->play();
        sound->setLoops(-1);

    });

    //暂停游戏控件
    stopBtn->move(830,200);
    stopBtn->setText("暂停游戏");
    stopBtn->setFont(font);
    connect(stopBtn,&QPushButton::clicked,[=]{
        isready=false;
        timer->stop();
        sound->stop();
    });

    //设置上下左右按键
    QPushButton* up=new QPushButton(this);
    QPushButton* down=new QPushButton(this);
    QPushButton* left=new QPushButton(this);
    QPushButton* right=new QPushButton(this);

    up->setText("↑");
    down->setText("↓");
    left->setText("←");
    right->setText("→");

    up->move(880,300);
    down->move(880,380);
    left->move(840,340);
    right->move(920,340);

    up->setShortcut(QKeySequence(Qt::Key_W));
    down->setShortcut(QKeySequence(Qt::Key_S));
    left->setShortcut(QKeySequence(Qt::Key_A));
    right->setShortcut(QKeySequence(Qt::Key_D));

    up->setAutoRepeat(true);
    down->setAutoRepeat(true);
    left->setAutoRepeat(true);
    right->setAutoRepeat(true);

    up->setStyleSheet("QPushButton{border:0px;}");
    down->setStyleSheet("QPushButton{border:0px;}");
    left->setStyleSheet("QPushButton{border:0px;}");
    right->setStyleSheet("QPushButton{border:0px}");

    QFont font2("宋体",24);
    up->setFont(font2);
    down->setFont(font2);
    left->setFont(font2);
    right->setFont(font2);


    connect(up,&QPushButton::clicked,[=]{
        if(moveDirect!=move_direction::DOWN)
        {
            moveDirect=move_direction::UP;
        }
    });
    //connect(down,&QPushButton::clicked,this,&GameRoom::moveDown);
    connect(down,&QPushButton::clicked,[=]{
        if(moveDirect!=move_direction::UP)
        {
            moveDirect=move_direction::DOWN;
        }
    });

    connect(left,&QPushButton::clicked,[=]{
        if(moveDirect!=move_direction::RIGHT)
        {
            moveDirect=move_direction::LEFT;
        }
    });

    connect(right,&QPushButton::clicked,[=]{
        if(moveDirect!=move_direction::LEFT)
        {
            moveDirect=move_direction::RIGHT;
        }
    });

    //退出游戏控件
    QPushButton* ExitBtn=new QPushButton(this);
    QFont font3("宋体",20);
    ExitBtn->setText("退出游戏");
    ExitBtn->setFont(font3);
    ExitBtn->move(830,700);

    QMessageBox* msg=new QMessageBox(this);
    QPushButton* yesBtn=new QPushButton("是");
    QPushButton* noBtn=new QPushButton("否");

    msg->addButton(yesBtn,QMessageBox::ApplyRole);//给消息盒子添加控件
    msg->addButton(noBtn,QMessageBox::RejectRole);

    msg->setWindowTitle("贪吃蛇大作战");
    msg->setText("您真的要退出吗？");

    connect(ExitBtn,&QPushButton::clicked,[=]{
        msg->show();
        msg->exec();//事件轮询（等待用户输入）
        QSound::play(":res/clicked.wav");
        if(msg->clickedButton()==yesBtn)
        {
            this->close();
        }else
        {
            msg->close();
        }
    });


}

void GameRoom::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);//实例化画家对象

    QPixmap pic;

    pic.load(":res/game_room.png");
    painter.drawPixmap(0,0,800,this->height(),pic);

    //绘制蛇


    //绘制蛇头
    if(moveDirect==move_direction::UP)
    {
        pic.load(":res/up.png");
    }else if(moveDirect==move_direction::DOWN)
        pic.load(":res/down.png");
    else if(moveDirect==move_direction::LEFT)
        pic.load(":res/left.png");
    else pic.load(":res/right.png");


    auto snakeHead=snakeList.front();
    painter.drawPixmap(snakeHead.x(),snakeHead.y(),snakeHead.width(),snakeHead.height(),pic);


    //绘制蛇身
    pic.load(":res/body.png");
    for(int i=1;i<snakeList.size()-1;i++)
    {
        auto snakeBody=snakeList.at(i);//获取当前节点
        painter.drawPixmap(snakeBody.x(),snakeBody.y(),snakeBody.width(),snakeBody.height(),pic);
    }

    //绘制蛇尾
    auto snakeBack=snakeList.back();//获取尾节点
    painter.drawPixmap(snakeBack.x(),snakeBack.y(),snakeBack.width(),snakeBack.height(),pic);



    //绘制食物
    pic.load(":res/food.png");
    painter.drawPixmap(foodRect.x(),foodRect.y(),foodRect.width(),foodRect.height(),pic);

    //绘制分数
    pic.load(":res/sorce_bg.png");
    painter.drawPixmap(this->width()*0.85,this->height()*0.06,90,40,pic);

    QPen pen;//定义画笔
    pen.setColor(Qt::black);//设置画笔颜色
    painter.setPen(pen);//画家使用画笔
    QFont font("宋体",22);
    painter.setFont(font);
    painter.drawText(this->width()*0.9,this->height()*0.06,QString("%1").arg(snakeList.size()));


    //绘制游戏失败效果
    if(isOver())
    {
        QFont font("方正舒体",50);
        painter.setPen(pen);
        pen.setColor(Qt::red);
        painter.setFont(font);
        painter.drawText(this->width()*0.16,this->height()*0.5,QString("Game Over!"));

        QSound::play(":res/gameOver.wav");

        isready=false;
        timer->stop();//关闭定时器
        sound->stop();
    }

    //向文件写分数
    int c=snakeList.size();
    QFile file("F:/Qt/snake/history.txt");
    if(file.open(QIODevice::WriteOnly|QIODevice::Text))
    {
        QTextStream out(&file);
        int num=c;
        out<<num;
        file.close();

    }


}

void GameRoom::moveUP()
{
    QPointF leftTop;//左上角坐标
    QPointF rightBotton;//右下角坐标

    //定义头结点
    auto snakeNode=snakeList.front();

    int headX=snakeNode.x();
    int headY=snakeNode.y();

    if(headY<0)
    {
        leftTop=QPointF(headX,this->height()-SnakeHeight);
    }
    else
    {
        leftTop=QPointF(headX,headY-SnakeHeight);
    }
    rightBotton=QPointF(leftTop.x()+SnakeWidth,leftTop.y()+SnakeHeight);
    snakeList.push_front(QRectF(leftTop,rightBotton));
}

void GameRoom::moveDown()
{
    QPointF leftTop;//左上坐标
    QPointF rightBotton;//右下坐标

    auto headNode=snakeList.front();

    int headX=headNode.x();
    int headY=headNode.y();

    if(headY>this->height()-SnakeHeight)
    {
        leftTop=QPointF(headX,0);
    }
    else
    {
        leftTop=headNode.bottomLeft();//获取左下角坐标
    }
    rightBotton=leftTop+QPointF(SnakeWidth,SnakeHeight);
    snakeList.push_front(QRectF(leftTop,rightBotton));

}

void GameRoom::moveLeft()
{
    QPointF leftTop;
    QPointF rightBotton;

    auto headNode=snakeList.front();
    int headX=headNode.x();
    int headY=headNode.y();

    if(headX<0)
    {
        leftTop=QPointF(800-SnakeWidth,headY);
    }else
    {
        leftTop=QPointF(headX-SnakeWidth,headY);
    }
    rightBotton=leftTop+QPointF(SnakeWidth,SnakeHeight);
    snakeList.push_front(QRectF(leftTop,rightBotton));
}

void GameRoom::moveRight()
{
    QPointF leftTop;
    QPointF rightBotton;

    auto headNode=snakeList.front();
    int headX=headNode.x();
    int headY=headNode.y();

    if(headX>=(800-SnakeWidth))
    {
        leftTop=QPointF(0,headY);
        //return;
    }else
    {
        leftTop=QPointF(headX+SnakeWidth,headY);
    }
    rightBotton=leftTop+QPointF(SnakeWidth,SnakeHeight);
    snakeList.push_front(QRectF(leftTop,rightBotton));

}

bool GameRoom::isOver()
{
//    auto snakeNode=snakeList.front();
//    int headX=snakeNode.x();
//    int headY=snakeNode.y();

//    if(0<headX<800&&0<headY<800)
//    {
//        for(int i=0;i<snakeList.size();i++)
//        {
//            for(int j=0;j<snakeList.size();j++)
//            {
//                if(snakeList.at(i)==snakeList.at(j))
//                {
//                    return true;
//                }
//            }
//        }
//    }
//    else return true;
    for(int i=0;i<snakeList.size();i++)
    {
        for(int j=i+1;j<snakeList.size();j++)
        {
            if(snakeList.at(i)==snakeList.at(j))
            {
                return true;
            }
        }
    }
    return false;
}

void GameRoom::createNewFood()
{
    foodRect=QRectF(qrand()%(800/SnakeWidth)*SnakeWidth,
                    qrand()%(800/SnakeHeight)*SnakeHeight,
                    SnakeWidth,SnakeHeight);
}
